package com.banciyuan.bcywebview.base.view.textview;


import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.utils.string.NoLineClickSpan;

public class EllipsezeTextView extends AppCompatTextView {
    private boolean addSpan;
    private String uname;
    private String uid;
    private Context mContext;

    public EllipsezeTextView(Context context) {
        super(context);
        mContext = context;
    }

    public EllipsezeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public EllipsezeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        resetText();
    }

    private void resetText() {
        Layout layout = getLayout();
        if (null == layout)
            return;
        CharSequence text = getText();
        if (layout.getLineCount() >= 3) {
            int lineEndPos = layout.getLineEnd(2);
            if (lineEndPos < text.length()) {
                CharSequence oldStr = text.subSequence(0, lineEndPos - 2);
                text = oldStr + "...";
            }
        }
        if (addSpan) {
            SpannableString sps = new SpannableString(text);
            NoLineClickSpan no = new NoLineClickSpan(uid, mContext, R.color.blue);
            sps.setSpan(no, 0, uname.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            setText(sps);
            setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            setText(text);
        }
    }

    public void setText(CharSequence text, String uname, String uid, boolean addSpan) {
        this.uname = uname;
        this.uid = uid;
        this.addSpan = addSpan;
        setText(text);
        resetText();
    }

}
